import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login'
import home from '@/views/home'
import welcome from '@/views/welcome'
import users from '@/views/user'
import rights from '@/views/rights'
import roles from '@/views/roles'
import cate from '@/views/cate'
import params from '@/views/params'
import list from '@/views/goods/list'
import add from '@/views/goods/add'
import orders from '@/views/orders'
import reports from '@/views/reports'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: login },
  {
    path: '/home',
    component: home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: welcome },
      { path: '/users', component: users },
      { path: '/rights', component: rights },
      { path: '/roles', component: roles },
      { path: '/categories', component: cate },
      { path: '/params', component: params },
      { path: '/goods', component: list },
      { path: '/goods/add', component: add },
      { path: '/orders', component: orders },
      { path: '/reports', component: reports }

    ]
  }

]

const router = new VueRouter({
  routes
})
// 导航守卫，判断是否登录,前置守卫
router.beforeEach((to, from, next) => {
  NProgress.start()
  // 如果用户访问的是登录页，就放行
  if (to.path === '/login') return next()
  // 将token 值 保存
  const tokenStr = window.sessionStorage.getItem('token')
  // 判断是否有 token ，没有就跳转到登录页
  if (!tokenStr) return next('/login')
  next()
})

// 后置守卫
router.afterEach((to, from) => {
  NProgress.done()
})

export default router
